﻿// WebZHX.Infrastructure/Repositories/Base/EfRepository.cs
using Common.Models;
using Core.Interfaces;
using Infrastructure.Data;
using Infrastructure.Extensions;
using Infrastructure.Services;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;

namespace Infrastructure.Repositories.Base
{
    /// <summary>
    /// EF Core 基础仓储
    /// </summary>
    /// <typeparam name="TEntity">实体类型</typeparam>
    /// <typeparam name="TKey">主键类型</typeparam>
    public class EfRepository<TEntity, TKey> : IBaseRepository<TEntity, TKey>, IPagedRepository<TEntity, TKey>
        where TEntity : class, IEntity<TKey>
    {
        protected readonly ApplicationDbContext _context;
        protected readonly DbSet<TEntity> _dbSet;

        public EfRepository(ApplicationDbContext context)
        {
            _context = context;
            _dbSet = context.Set<TEntity>();
        }
        public FileLoggerService LOG = new FileLoggerService();
        /// <summary>
        /// 根据主键获取实体
        /// </summary>
        public virtual async Task<TEntity> GetByIdAsync(TKey id)
        {
            return await _dbSet.FindAsync(id);
        }

        /// <summary>
        /// 获取所有实体
        /// </summary>
        public virtual async Task<IEnumerable<TEntity>> GetAllAsync()
        {
            return await _dbSet.ToListAsync();
        }

        /// <summary>
        /// 新增实体
        /// </summary>
        public virtual async Task<TEntity> AddAsync(TEntity entity)
        {
            //entity.CreatedTime = DateTime.UtcNow;
            var result = await _dbSet.AddAsync(entity);
            await _context.SaveChangesAsync();
            return result.Entity;
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        public virtual async Task<TEntity> UpdateAsync(TEntity entity)
        {
            //entity.UpdatedTime = DateTime.UtcNow;
            _dbSet.Attach(entity);
            _context.Entry(entity).State = EntityState.Modified;
            await _context.SaveChangesAsync();
            return entity;
        }
        // 在 EfRepository 类中添加
        /// <summary>
        /// 局部更新实体（只更新非null字段）
        /// </summary>
        public virtual async Task<TEntity> PartialUpdateAsync(TEntity entity)
        {
            var existingEntity = await _dbSet.FindAsync(entity.Id);
            if (existingEntity == null)
                return null;

            // 获取实体类型和所有属性
            var entityType = typeof(TEntity);
            var properties = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var property in properties)
            {
                // 跳过主键和导航属性
                if (property.Name == "Id")
                    continue;

                // 获取新值
                var newValue = property.GetValue(entity);

                // 如果新值不为null，则更新
                if (newValue != null)
                {
                    // 对于字符串，空字符串也视为有值
                    if (property.PropertyType == typeof(string) && string.IsNullOrEmpty(newValue as string))
                    {
                        // 空字符串也更新
                        property.SetValue(existingEntity, newValue);
                    }
                    else if (property.PropertyType != typeof(string))
                    {
                        // 非字符串类型，直接更新非null值
                        property.SetValue(existingEntity, newValue);
                    }
                    else
                    {
                        // 非空字符串，更新
                        property.SetValue(existingEntity, newValue);
                    }
                }
            }

            // 自动设置更新时间
            //existingEntity.UpdatedTime = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return existingEntity;
        }

        /// <summary>
        /// 删除实体（物理删除）
        /// </summary>
        public virtual async Task<bool> DeleteAsync(TKey id)
        {
            var entity = await GetByIdAsync(id);
            if (entity == null) return false;

            _dbSet.Remove(entity);
            return await _context.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 软删除实体
        /// </summary>
        public virtual async Task<bool> SoftDeleteAsync(TKey id)
        {
            var entity = await GetByIdAsync(id);
            if (entity == null) return false;

            entity.IsDeleted = true;
            //entity.UpdatedTime = DateTime.UtcNow;
            return await _context.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public virtual async Task<PagedResult<TEntity>> GetPagedAsync(int pageIndex, int pageSize, string orderBy = "Id")
        {
            var query = _dbSet.AsNoTracking();

            var totalCount = await query.CountAsync();
            var data = await query
                .OrderByDynamic(orderBy)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            return new PagedResult<TEntity>
            {
                Data = data,
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalCount = totalCount
            };
        }

        /// <summary>
        /// 分页查询（带过滤条件）
        /// </summary>
        public virtual async Task<PagedResult<TEntity>> GetPagedAsync(QueryFilter filter)
        {
            try
            {
                var query = _dbSet.AsNoTracking();

                // 应用过滤条件
                query = ApplyFilterConditions(query, filter.Conditions);
                // 调试：输出生成的 SQL
                var sql = query.ToQueryString();

                var totalCount = await query.CountAsync();
                var data = await query
                    .OrderByDynamic(filter.OrderBy, filter.IsAscending)
                    .Skip((filter.PageIndex - 1) * filter.PageSize)
                    .Take(filter.PageSize)
                    .ToListAsync();

                return new PagedResult<TEntity>
                {
                    Data = data,
                    PageIndex = filter.PageIndex,
                    PageSize = filter.PageSize,
                    TotalCount = totalCount
                };
            }
            catch (Exception ex)
            {
                LOG.LogException(ex);
                throw ex;
            }
            
        }

        /// <summary>
        /// 应用过滤条件
        /// </summary>
        /// <param name="query">查询</param>
        /// <param name="conditions">条件</param>
        /// <returns>新的查询</returns>
        private IQueryable<TEntity> ApplyFilterConditions(IQueryable<TEntity> query, List<FilterCondition> conditions)
        {
            try
            {
                foreach (var condition in conditions)
                {
                    query = query.WhereDynamic(condition.Field, condition.Operator, condition.Value);
                }
                return query;
            }
            catch (Exception ex)
            {

                throw;
            }
           
        }
    }
}